import menuClose from "@/assets/common/svgs/menuClose.svg";
import menuOpen from "@/assets/common/svgs/menuOpen.svg";
import { getRowByField } from "@/hy_dev_lib/src";
import { dispatchPubsub } from "@/hy_dev_lib/src/store";
import { useGlobalContent } from "@/store";
import { AppstoreOutlined } from "@ant-design/icons";
import { Layout, Menu, MenuProps } from "antd";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { ReactSVG } from "react-svg";
import { SideMenuProps } from "./";
import "./sidemenu.less";

const { Sider } = Layout;

export default function SideMenu(props: SideMenuProps) {
  const { menuData, changeMenuKey } = props;
  const navigate = useNavigate();
  const location = useLocation();
  const [openMenuKeys, setOpenMenuKeys] = useState<string[]>([]);
  const { global, globalDispatch } = useGlobalContent();
  const [menuCollapsed, setMenuCollapsed] = useState<boolean>(false);
  const { sideMenuSelectData } = global || {};
  const selMenuPath = sideMenuSelectData?.cdlj;
  const pathname = location.pathname;

  // useEffect(() => {
  //   const menuSId = subscribePubsub("GO_TO_PAGE", (data: any) => {
  //     const { url, state } = data;
  //     onSelect(url, state);
  //     openSubMenu(url);
  //   });

  //   return () => {
  //     unSubscribePubsub(menuSId);
  //   };
  // }, [menuData]);

  //当此时选中的是子菜单时，展开对应的父级菜单
  const openSubMenu = (selMenuKey: string) => {
    let list: string[] = [];
    const getPathList = (arr: any[], pPath: string[] = []) => {
      arr.map((item: any) => {
        if (item.cdlj === selMenuKey) {
          list = pPath;
        } else if (item?.children?.length) {
          getPathList(item?.children, [...pPath, item.cdlj]);
        }
      });
    };
    getPathList(menuData, []);
    setOpenMenuKeys([...new Set([...list, ...openMenuKeys])]);
  };

  // 路径是否在才菜单列表中
  const pathInMenuList = (path: string, list: any[]) => {
    let t = false;
    const v = (arr: any[]) => {
      arr.map((item: any) => {
        if (item.children?.length > 0) {
          v(item.children);
        } else if (path === item.cdlj) {
          t = true;
        }
      });
    };
    v(list);
    return t;
  };

  useEffect(() => {
    if (!menuData?.length || !pathname) return;
    const str = pathname.substring(5);
    if (pathInMenuList(str, menuData)) {
      openSubMenu(str);
      globalDispatch({
        type: "sideMenuSelectData",
        data: getRowByField(menuData, str, "cdlj")!!,
      });
    } else {
      globalDispatch({
        type: "sideMenuSelectData",
        data: {},
      });
    }
  }, [menuData, pathname]);

  const onSelect = (key: any, state?: any) => {
    if (key === selMenuPath) {
      changeMenuKey();
      dispatchPubsub("CLOSE_FLOW_DETAIL", {});
      // 关闭所有有onClose事件的抽屉
      dispatchPubsub("CLOSE_ALL_DRAWER", {});
      return;
    }
    globalDispatch({
      type: "sideMenuSelectData",
      data: getRowByField(menuData, key, "cdlj")!!,
    });
    if (!key?.startsWith("/")) return navigate(`/home/${key}`, { state });
    navigate(`/home${key}`, { state });
  };

  const onMenuCollapsed = (val: boolean) => {
    dispatchPubsub("RESET_TABLE_WIDTH", {});
    setMenuCollapsed(val)
  };

  const onOpenChange: MenuProps["onOpenChange"] = (keys) => {
    // 本次打开的菜单
    const latestOpenKey = keys.find((key) => openMenuKeys.indexOf(key) === -1);
    // 展开的是一级菜单
    if (latestOpenKey && menuData.findIndex((item: any) => item.cdlj === latestOpenKey) !== -1) {
      setOpenMenuKeys(latestOpenKey ? [latestOpenKey] : []);
    } else {
      setOpenMenuKeys(keys);
    }
  };

  const getMenuList = (menuList: any[], selMenuPath: string) => {
    const renderMenu = (menuArr: any[], level: number): any => {
      return menuArr?.map((item) => {
        // 子级或子级本身被选中
        const selected = item.cdlj === selMenuPath || getRowByField(item.children || [], selMenuPath, "cdlj");
        const obj: any = {};
        if (item?.children?.length) {
          obj.children = renderMenu(item?.children, level + 1);
        }
        const iconSrc = selected ? item.cdxztbdz : item.cdtbdz;
        return {
          key: item.cdlj || item.tid,
          icon: !level ? iconSrc ? <img src={SYSTEM_GLOBAL.fileBaseURL + iconSrc} /> : <AppstoreOutlined /> : null,
          ...obj,
          // children,
          label: item.cdmc,
          menuid: item.tid,
          // ...rest,
          // type,
        };
      });
    };
    return renderMenu(menuList, 0);
  };

  return (
    <Sider
      width={200}
      collapsed={menuCollapsed}
      collapsedWidth={61}
      onCollapse={(value) => onMenuCollapsed(value)}
      className={menuCollapsed ? "home-sider-menu sider-menu" : "home-sider-menu "}
    >
      <Menu
        className="siderMenu"
        mode="inline"
        selectedKeys={[sideMenuSelectData?.cdlj]}
        items={getMenuList(menuData, selMenuPath)}
        // onSelect={(e) => onSelect(e.key)}
        // 用 onClick 不用 onSelect？onSelect点击相同菜单不会触发
        onClick={(e) => onSelect(e.key)}
        openKeys={openMenuKeys}
        inlineIndent={20}
        onOpenChange={onOpenChange}
      ></Menu>
      {menuCollapsed ? (
        <div
          className="collapse-btn pointer"
          onClick={() => {
            onMenuCollapsed(false);
          }}
        >
          <ReactSVG className="react-svg" src={menuOpen}></ReactSVG>
        </div>
      ) : (
        <div
          className="collapse-btn pointer"
          onClick={() => {
            onMenuCollapsed(true);
          }}
        >
          <ReactSVG className="react-svg" src={menuClose}></ReactSVG>
        </div>
      )}
    </Sider>
  );
}
